package net.joyphper.commons.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;

public class Tools {
	public static void main(String[] agrs){
		System.out.println(Tools.isMobile("18073113117"));
	}
	/**
	 * 检测字符串是否为空(null,"","null")
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s){
		return s==null || "".equals(s.trim()) || "null".equals(s.trim()) || "undefined".equals(s.trim());
	}
	
	/**
	 * 验证是否为E-mail
	 * @param s
	 * @return
	 */
	public static boolean isMail(String s){
		return s!=null && s.toLowerCase().matches("([a-z0-9_\\-\\.])+@([a-z0-9_\\-])+((.[a-z]{2,3}){1,2})");
	}
	
	/**
	 * 验证是否为手机
	 * @param s
	 * @return
	 */
	public static boolean isMobile(String s){
		return s!=null && s.matches("1[3|5|8|4][0-9]{1}[0-9]{8}");
	}
	
	/**
	 * 验证是否可以做登录名
	 * @param s
	 * @return
	 */
	public static boolean loginNameEnable(String s){
		return s!=null && s.matches("[0-9a-zA-Z_\\-\\.]{4,20}") && !s.toLowerCase().equals("anonymous");
	}
	
	/**
	 * 验证是否为合法的数字ID
	 * @param s
	 * @return
	 */
	public static boolean isIntId(String s){
		return s!=null && s.matches("[1-9]{1}[0-9]{0,10}");
	}
	/**
	 * 生成随机码
	 * @param len	长度
	 * @param isNumber 是否为全数字
	 * @return
	 */
	public static String getRandCode(int len,boolean isNumber){
		String[] codes = new String[]{
				"1","2","3","4","5","6","7","8","9","0",
				"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
		};
		Random random = new SecureRandom();
		String code = "";
		for(int i = 0; i < len ; i++){
			if(isNumber){
				code+=codes[random.nextInt(9)];
			}else{
				code+=codes[random.nextInt(35)];
			}
		}
		return code;
	}
	/** 
     * 获得一个UUID 
     * @return String UUID 
     */ 
    public static String getUUID(){ 
    	try{
			// Generate a byte array containing a session identifier
			Random random = new SecureRandom(); // 取随机数发生器, 默认是SecureRandom
			byte[] bytes = new byte[16];
	
			random.nextBytes(bytes); // 产生SESSION_ID_BYTES字节的byte
			
			bytes = MessageDigest.getInstance("MD5").digest(bytes); // 取摘要,默认是"MD5"算法
			
			// Render the result as a String of hexadecimal digits
	
			StringBuffer result = new StringBuffer();
	
			for (int i = 0; i < bytes.length; i++) { // 转化为16进制字符串
	
				byte b1 = (byte) ((bytes[i] & 0xf0) >> 4);
	
				byte b2 = (byte) (bytes[i] & 0x0f);
	
				if (b1 < 10)
					result.append((char) ('0' + b1));
				else
					result.append((char) ('a' + (b1 - 10)));
	
				if (b2 < 10)
					result.append((char) ('0' + b2));
				else
					result.append((char) ('a' + (b2 - 10)));
			}
			return (result.toString());
		}catch(Exception e){
			return null;
		}
    }
    
}
